package com.bjsdzk.collector.controller;

import java.io.IOException;
import java.util.*;

import org.bouncycastle.jcajce.provider.digest.MD2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.*;

import com.bjsdzk.collector.constant.Constant;
import com.bjsdzk.collector.entity.HttpClientResult;
import com.bjsdzk.collector.utils.HttpClientUtils;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;



@RestController
@RequestMapping("/alerts")
public class AlertsController {

	private static final Logger logger = LoggerFactory.getLogger(AlertsController.class);
	private final OkHttpClient client = new OkHttpClient();

	private ConfigurableApplicationContext context;


    @PostMapping("/alerts")
    public String receive(@RequestBody String body) throws JSONException, IOException  {
    	logger.info("data receive:  body String --- " +body);
    	String title = new JSONObject(body).getJSONObject("check_result").getJSONObject("triggered_condition").getString("title");
    	logger.info("alerts type :" +title);
    	if("countless".equals(title)) {
    	}else if("countmore".equals(title)) {
    		
    	}
    	Map<String, String> params = new HashMap<String, String>();
        params.put("type", title);
		params.put("source", "after");
        HttpClientResult result = null;
		String[] profiles = context.getEnvironment().getActiveProfiles();
		String address;
		try {
			if (Arrays.asList(profiles).contains("dev")){
				address=Constant.TEST_ALERT;
			}else {
				address=Constant.ALERT;
			}
			result = HttpClientUtils.doPost(address, params);
		} catch (Exception e) {
			logger.info("invoke flatform alerts fail");
			e.printStackTrace();
		}
        System.out.println(result);    	
        return "ok";
    }

}
